package pw.mcdarc.mc.bython.Event;

import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.event.Event;
import pw.mcdarc.mc.bython.Bython;
import pw.mcdarc.mc.bython.Gui.getGui;
import pw.mcdarc.mc.bython.Nms.getNMS;
import pw.mcdarc.mc.bython.Pool.TempStore;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

/*
This file is part of Bython.
Dont remove this header anytime.
Under the Apache2 License.
You can't sell it, repost it, share it without permission.
Date: 八月,27,2016
*/

public class EventHooker {
    public static void hook(Event event) {
//        System.out.println(event.getEventName());
        if (Bython.Events.isEmpty()) {
            return;
        }
        Iterator iter = Bython.Events.entrySet().iterator();
        while(iter.hasNext())
        {
            Map.Entry element = (Map.Entry)iter.next();
            String listenerName = (String)element.getKey();
            String value = (String)element.getValue();
            String fileName = value.split(",")[0] + ".py";
            String[] splited = listenerName.split("\\.");
            if (event.getEventName().equalsIgnoreCase(splited[splited.length-1]))
            {
                File scriptFile = new File(Bython.i.getDataFolder() + "/" + fileName);
                if (!Bython.LoadedFiles.contains(scriptFile)) {return;}
                String scriptText = "";
                try {
                    scriptText = FileUtils.readFileToString(scriptFile);
                } catch (IOException e) {
                    Bukkit.getLogger().warning("Bython目录下权限错误");
                }
                ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
                try {
                    engine.eval(scriptText);
                    engine.put("gui", new getGui());
                    engine.put("pool", new TempStore());
                    engine.put("nms", new getNMS());
                    engine.put("event", event);
                    engine.eval(value.split(",")[1]);
                } catch (ScriptException e) {
                    e.printStackTrace();
                }
            }
            // 如果else里return了，那么这个函数就直接返回了。
            // else {
            //     return;
            // }
        }
    }
}
